﻿using AutoMapper;
using B.S.ProcessEgine.API.Applocations.Commands.FormInfoCommand;
using B.S.ProcessEgine.API.Dtos.RequestDto;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormInfohandler
{
    public class GetFormListCommandHandler : IRequestHandler<GetFormListCommand, ApiResult<ApiPaging<FormResponseDto>>>
    {
        private readonly IFormInfoRepository _formRepository;
        private readonly IFormTypeRepository _formTypeRepository;
        private readonly ILogger<GetFormListCommandHandler> _logger;
        private readonly IMapper _mapper;

        public GetFormListCommandHandler(IFormInfoRepository formRepository, ILogger<GetFormListCommandHandler> logger, IMapper mapper, IFormTypeRepository formTypeRepository)
        {
            _formRepository = formRepository;
            _logger = logger;
            _mapper = mapper;
            _formTypeRepository = formTypeRepository;
        }

        public async Task<ApiResult<ApiPaging<FormResponseDto>>> Handle(GetFormListCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //获取表单列表
                var formInfo = _formRepository.GetAll().Where(x => x.IsDel == false);
                var formTypeInfo = _formTypeRepository.GetAll().Where(x => x.IsDel == false);

                //根据表单编号查询
                if (!string.IsNullOrEmpty(request.FormName))
                {
                    formInfo = formInfo.Where(x => x.FormName.Contains(request.FormName));
                }

                //根据行业 id 来查询
                if (request.ProfessionalId != null)
                {
                    formTypeInfo = formTypeInfo.Where(x => x.ProfessionalId == request.ProfessionalId);
                }

                //根据表单分类筛选
                if (request.TypeId != null)
                {
                    formInfo = formInfo.Where(x => x.TypeId == request.TypeId);
                }

                //linq查询
                var query = from form in formInfo
                            join type in formTypeInfo on form.TypeId equals type.TypeId into temp
                            from type in temp.DefaultIfEmpty()
                            select new FormResponseDto
                            {
                                FormId = form.FormId,
                                FormName = form.FormName,
                                FormNo = form.FormNo,
                                TypeId = form.TypeId,
                                TypeName = type.TypeName,
                                TypeNo=type.TypeNo,
                                ProfessionalId = type.ProfessionalId
                            };

                // 计算总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 执行分页查询
                var formList = new ApiPaging<FormResponseDto>(
                    totalCount,
                    (int)Math.Ceiling(totalCount / (double)request.PageSize),
                    await query.Skip((request.PageIndex - 1) * request.PageSize)
                        .Take(request.PageSize)
                        .ToListAsync(cancellationToken)
                );

                return ApiResult<ApiPaging<FormResponseDto>>.Success(formList, StateCodeEnum.Ok);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "GetFormListCommandHandler Error");
                return ApiResult<ApiPaging<FormResponseDto>>.Fail(null,StateCodeEnum.Exception, "获取表单列表异常");
            }
        }
    }
}
